/*this file has some code is similar to the file article.js  */

var index =  getRootPath() + "load?";
var categoryId = -1;
var tagIds = new Array();

$(function(){
    loadList(index);
})

function toIndex(){
    if(categoryId != -1){
        $("#c_" + categoryId).removeClass('active');
        categoryId=-1;
    }

    for(var i=0; i < tagIds.length;i++){
        $('#t_' + tagIds[i]).removeClass('active');
    }
    tagIds.splice(0,tagIds.length);

    loadList(index);
}

function toCategory(id){
    var category  = $("#c_" + id);

    if(category.hasClass('active')){
        category.removeClass('active');
        categoryId=-1;
    }else{
        if(categoryId!=-1) {
            $("#c_" + categoryId).removeClass('active');
        }

        category.addClass('active');
        categoryId=id;
    }

    loadList(index);
}

function toTag(id){

    if( $("#t_" + id).hasClass("active")){;
        tagIds.splice($.inArray(id,tagIds),1);
        $("#t_" + id).removeClass('active');
    }else{
        $("#t_" +id).addClass('active');
        tagIds.push(id);
    }

    loadList(index);
}

function toPage(PageNum){
    var pages = $('#pages').val();
    var paging = index;


    if(PageNum >0 && PageNum <=pages){
        paging = paging + "pageNum=" + PageNum;
    }else{
        return false;
    }

    loadList(paging);
}

function search(){
    loadList(index);
}

function loadList(url){
    var param = buildParam();
    url = url + '&param=' +  param;

    $.ajax({
        url:url,
        type:'post',
        success:function(data){
            $('.article-list').html(data);
        }
    })
}

function buildParam(){
    var param = {};

    var keyword = $('#keyword').val();
    if( !isEmpty(keyword) ) {
        param["title"] = keyword
    }


    if(categoryId != -1){
        param["categoryId"] = categoryId;
    }

    param["tagIds"] = tagIds;

    return JSON.stringify(param);
}

function getRootPath() {
    //获取当前网址，如： http://localhost:8080/GameFngine/share/meun.jsp
    var curWwwPath = window.document.location.href;
    //获取主机地址之后的目录，如： GameFngine/meun.jsp
    var pathName = window.document.location.pathname;
    var pos = curWwwPath.indexOf(pathName);
    //获取主机地址，如： http://localhost:8080
    var localhostPaht = curWwwPath.substring(0, pos);
    //获取带"/"的项目名，如：/GameFngine
    pos = pathName.substr(1).indexOf('/');
    if(pos == -1) {
        pos =  pathName.substr(1).length + 1 ;
    }
    var projectName = pathName.substring(0,  pos);
    return (localhostPaht + projectName + "/");
}

function isEmpty(str){
    if (!str || $.trim(str).length <= 0)
        return true;
    return false;
}